#!/usr/bin/env python3
"""
路由模板 - 后端

使用说明：
1. 复制此文件到 apps/backend/routes/
2. 重命名文件（例如：my_new_route.py）
3. 搜索并替换所有 [TODO] 标记的内容
4. 在 app.py 中导入并注册此蓝图
"""

from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from models import db
# [TODO] 导入需要的模型
# from models import YourModel

# [TODO] 修改蓝图名称
bp = Blueprint('template', __name__)


# ==================== GET - 获取列表 ====================
@bp.route('/', methods=['GET'])
@jwt_required()  # [TODO] 如果不需要认证，删除此装饰器
def get_items():
    """获取所有项目"""
    try:
        # [TODO] 如果需要用户认证，获取当前用户ID
        current_user_id = int(get_jwt_identity())
        
        # [TODO] 修改查询逻辑
        # items = YourModel.query.filter_by(user_id=current_user_id).all()
        
        # 示例：返回模拟数据
        items = [
            {'id': 1, 'name': '示例项目1', 'description': '这是示例'},
            {'id': 2, 'name': '示例项目2', 'description': '这是示例'},
        ]
        
        return jsonify({
            'success': True,
            'data': items,
            # [TODO] 添加或修改返回字段
        }), 200
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


# ==================== GET - 获取单个项目 ====================
@bp.route('/<int:item_id>', methods=['GET'])
@jwt_required()
def get_item(item_id):
    """获取单个项目"""
    try:
        current_user_id = int(get_jwt_identity())
        
        # [TODO] 修改查询逻辑
        # item = YourModel.query.filter_by(
        #     id=item_id, 
        #     user_id=current_user_id
        # ).first()
        # 
        # if not item:
        #     return jsonify({'error': '项目不存在'}), 404
        
        # 示例：返回模拟数据
        item = {'id': item_id, 'name': f'项目{item_id}'}
        
        return jsonify({
            'success': True,
            'data': item,
        }), 200
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


# ==================== POST - 创建 ====================
@bp.route('/', methods=['POST'])
@jwt_required()
def create_item():
    """创建新项目"""
    try:
        current_user_id = int(get_jwt_identity())
        data = request.get_json()
        
        # [TODO] 添加数据验证
        if not data or not data.get('name'):
            return jsonify({'error': '名称不能为空'}), 400
        
        # [TODO] 创建数据库记录
        # new_item = YourModel(
        #     user_id=current_user_id,
        #     name=data['name'],
        #     description=data.get('description', '')
        # )
        # 
        # db.session.add(new_item)
        # db.session.commit()
        
        # 示例：返回模拟数据
        new_item = {
            'id': 1,
            'name': data['name'],
            'description': data.get('description', '')
        }
        
        return jsonify({
            'success': True,
            'data': new_item,
            'message': '创建成功'
        }), 201
        
    except Exception as e:
        # db.session.rollback()
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


# ==================== PUT - 更新 ====================
@bp.route('/<int:item_id>', methods=['PUT'])
@jwt_required()
def update_item(item_id):
    """更新项目"""
    try:
        current_user_id = int(get_jwt_identity())
        data = request.get_json()
        
        # [TODO] 查询并验证权限
        # item = YourModel.query.filter_by(
        #     id=item_id,
        #     user_id=current_user_id
        # ).first()
        # 
        # if not item:
        #     return jsonify({'error': '项目不存在'}), 404
        
        # [TODO] 更新字段
        # if 'name' in data:
        #     item.name = data['name']
        # if 'description' in data:
        #     item.description = data['description']
        # 
        # db.session.commit()
        
        # 示例：返回模拟数据
        updated_item = {
            'id': item_id,
            'name': data.get('name', '更新后的名称'),
        }
        
        return jsonify({
            'success': True,
            'data': updated_item,
            'message': '更新成功'
        }), 200
        
    except Exception as e:
        # db.session.rollback()
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


# ==================== DELETE - 删除 ====================
@bp.route('/<int:item_id>', methods=['DELETE'])
@jwt_required()
def delete_item(item_id):
    """删除项目"""
    try:
        current_user_id = int(get_jwt_identity())
        
        # [TODO] 查询并验证权限
        # item = YourModel.query.filter_by(
        #     id=item_id,
        #     user_id=current_user_id
        # ).first()
        # 
        # if not item:
        #     return jsonify({'error': '项目不存在'}), 404
        # 
        # db.session.delete(item)
        # db.session.commit()
        
        return jsonify({
            'success': True,
            'message': '删除成功'
        }), 200
        
    except Exception as e:
        # db.session.rollback()
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


# ==================== 自定义端点示例 ====================
@bp.route('/custom-action', methods=['POST'])
@jwt_required()
def custom_action():
    """自定义操作"""
    try:
        current_user_id = int(get_jwt_identity())
        data = request.get_json()
        
        # [TODO] 实现自定义逻辑
        
        return jsonify({
            'success': True,
            'message': '操作成功',
            'data': {}
        }), 200
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

